import 'package:enhance_stepper/enhance_stepper.dart';
import 'package:flutter/material.dart';
import '../../utils/g.dart';
import '../../utils/payment.dart';
import '../../utils/order_types.dart';

import 'package:provider/provider.dart';
import '../../providers/comment_provider.dart';

class OrderDetail extends StatefulWidget {
  String uni;
  OrderDetail({Key? key, required String this.uni }) : super(key: key);

  @override
  _OrderDetailState createState() => _OrderDetailState();
}

class _OrderDetailState extends State<OrderDetail> {
  Map order = {};
  var _futureInstance;
  List types = getOrderTypes();

  @override
  void initState() { 
    super.initState();
    _futureInstance = G.api.order.detail(widget.uni);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('订单详情'),
        centerTitle: true,
      ),
      body: FutureBuilder(
        future: _futureInstance,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            var res = snapshot.data as Map;
            if (res['status'] == 200) {
              order = res['data'];

              return Container(
                color: Colors.grey.shade200,
                child: ListView(
                  children: [
                    _renderOrderStatus(),
                    _renderUserAddress(),
                    _renderOrderProduct(),
                    _renderServiceCall(),
                    _renderOrderDetail(),
                    _renderDeliveryInfo(),
                    _renderOrderAmount(),
                  ],
                ),
              );
            } else {
              // 报错
              G.error('查询订单详情失败');
            }
          } else if (snapshot.hasError) {
            return Center(
              child: Text("${snapshot.error}"),
            );
          }

          return G.loader();
        }
      ),
      bottomNavigationBar: _getBottomMenu(context),
    );
  }

  Widget _renderOrderStatus() {
    return Container(
      padding: const EdgeInsets.all(1),
      height: 90,
      child: EnhanceStepper(
        stepIconSize: 30,
        type: StepperType.horizontal,
        horizontalTitlePosition: HorizontalTitlePosition.bottom,
        horizontalLinePosition: HorizontalLinePosition.top,
        physics: const ClampingScrollPhysics(),
        steps: types.map((item) {
          return EnhanceStep(
            title: Text(item['title']), 
            content: Text(item['key'].toString()),
            icon: order['_status']['_type'] >= item['key']
              ? const Icon(Icons.check_circle, color: Colors.blue, size: 30)
              : const Icon(Icons.watch_later, color: Colors.grey, size: 30),
            state: order['_status']['_type'] >= item['key']
              ? StepState.complete
              : StepState.disabled,
            isActive: order['_status']['_type'] >= item['key']
              ? true
              : false
          );
        }).toList()
      ),
    );
  }

  Widget _renderUserAddress() {
    var userInfo = order['real_name'].toString()
                 + ", " + order['user_phone'].toString();
    var addressInfo = order['user_address'].toString();

    return Container(
      margin: const EdgeInsets.fromLTRB(10, 10, 10, 10),
      color: Colors.white,
      child: ListTile(
        title: Text(userInfo),
        subtitle: Text(addressInfo),
      ),
    );
  }

  Widget _renderOrderProduct() {
    return Wrap(
      spacing: 10.0,
      direction: Axis.horizontal,
      alignment: WrapAlignment.start,
      children: List<Widget>.generate(
        order['cartInfo'].length, (int index) {
          return Container(
            margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
            color: Colors.white,
            child: ListTile(
              isThreeLine: true,
              onTap: () {
                Map<String, dynamic> p = {
                  'id': order['cartInfo'][index]['product_id']
                };
                G.router.navigateTo(context, '/product_detail'+G.parseQuery(params: p));
              },
              leading: G.imageWidget(
                order['cartInfo'][index]['productInfo']['image'],
                width: 100,
                height: 100
              ),
              title: Text(
                order['cartInfo'][index]['productInfo']['store_name'].toString(),
                style: const TextStyle(
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
              subtitle: Column(
                children: [
                  Container(
                    width: 200,
                    child: Text(
                      order['cartInfo'][index]['productInfo']['attrInfo']['sku'],
                      style: const TextStyle(
                        fontSize: 16,
                      ),
                      overflow: TextOverflow.ellipsis,
                      textAlign: TextAlign.left,
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "￥ "+order['cartInfo'][index]['truePrice'].toString() + " X "+order['cartInfo'][index]['cart_num'].toString(),
                        style: TextStyle(
                          fontSize: 16,
                          color: Theme.of(context).primaryColor,
                          fontWeight: FontWeight.w500
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),

                      order['_status']['_type'] == 3
                      ?
                        order['cartInfo'][index]['is_reply'] == 1
                        ?
                        const Text('已评价')
                        :
                        InkWell(
                          onTap: () {
                            // 跳转到评价页面
                            Provider.of<CommentProvider>(context, listen: false).setProduct(order['cartInfo'][index]);

                            G.router.navigateTo(context, '/order_comment');
                          },
                          child: const Text(
                            '去评价',
                            style: TextStyle(color: Colors.blue)
                          ),
                        )
                      :
                      Container()
                    ],
                  )
                ],
              ),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
                side: BorderSide(
                  color: Colors.grey.shade400,
                  width: 1
                )
              ),
            )
          );
        }
      ).toList(),
    );
  }

  Widget _renderOrderDetail() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
      color: Colors.white,
      child: Column(
        children: [
          ListTile(
            title: const Text('订单编号'),
            trailing: Text(order['order_id'].toString()),
            dense: true,
          ),
          ListTile(
            title: const Text('下单时间'),
            trailing: Text(order['_add_time'].toString()),
            dense: true,
          ),
          ListTile(
            title: const Text('支付方式'),
            trailing: Text(_getPaymentName()),
            dense: true,
          ),
          ListTile(
            title: const Text('支付金额'),
            trailing: Text(order['pay_price'].toString()),
            dense: true,
          ),
        ],
      )
    );
  }

  String _getPaymentName() {
    String target = "";
    List payment = getPayment();
    for (var item in payment) {
      if (item['value'] == order['pay_type']) {
        target = item['name'];
      }
    }

    return target;
  }

  Widget _renderServiceCall() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
      color: Colors.white,
      child: Center(
        child: InkWell(
          onTap: () {
            // 点击进入客服页面
          },
          child: Text(
            "联系客服",
            style: TextStyle(
              color: Theme.of(context).primaryColor,
              fontSize: 24,
              fontWeight: FontWeight.w500
            )
          ),
        )
      )
    );
  }

  Widget _renderDeliveryInfo() {
    return order['delivery_id'] == null
      ? Container()
      : Container(
        margin: const EdgeInsets.fromLTRB(10, 0, 10, 10),
        color: Colors.white,
        child: Column(
          children: [
            ListTile(
              title: const Text('配送方式'),
              trailing: Text(order['delivery_type']),
              dense: true,
            ),
            ListTile(
              title: const Text('快递公司'),
              trailing: Text(order['delivery_name']),
              dense: true,
            ),
            ListTile(
              title: const Text('快递号'),
              trailing: Text(order['delivery_id']),
              dense: true,
            ),
          ],
        )
      );
  }

  Widget _renderOrderAmount() {
    return Container(
      margin: const EdgeInsets.fromLTRB(10, 0, 10, 70),
      color: Colors.white,
      child: Column(
        children: [
          ListTile(
            title: const Text('商品总价'),
            trailing: Text(order['total_price'].toString()),
            dense: true,
          ),
          ListTile(
            title: const Text('实付款：'),
            trailing: Text(
              order['pay_price'].toString(),
              style: TextStyle(
                color: Theme.of(context).primaryColor,
                fontSize: 24,
                fontWeight: FontWeight.w500
              )
            ),
            dense: true,
          ),
        ],
      )
    );
  }

  Widget _getBottomMenu(context) {
    return Row(
      children: [
        InkWell(
          onTap: () {
            // 查看物流
          },
          child: Container(
            width: G.width / 2,
            height: 50,
            color: Colors.green,
            alignment: Alignment.center,
            child: const Text(
              "查看物流",
              style: TextStyle(
                color: Colors.white,
                fontSize: 22
              )
            ),
          ),
        ),
        InkWell(
          onTap: () {
            // 确认收货
          },
          child: Container(
            width: G.width / 2,
            height: 50,
            color: Theme.of(context).primaryColor,
            alignment: Alignment.center,
            child: const Text(
              "确认收货",
              style: TextStyle(
                color: Colors.white,
                fontSize: 22
              )
            ),
          ),
        )
      ],
    );
  }
}